<template>
  <div class="container">
    <ActionBar
      :page-no="11"
      :add-active="addActive"
      :del-active="delActive"
      :edit-active="editActive"
      :has-cancel="false"
      :has-edit="false"
      :has-save="false"
      :cancel-active="cancelActive"
      :save-active="saveActive"
      @add="add"
      @edit="edit"
      @del="del"
    />
    <div class="search-item-list">
      <div class="search-item">
        <div class="label">生长品种名称：</div>
        <div v-if="plantVarityList.length <= 8" class="value">
          <el-button
            v-for="(item,index) in plantVarityList"
            :key="index"
            type="info"
            plain
            size="mini"
            :class="{active: plantVarietyNo == item.plantVarietyNo}"
            @click="choosePlantVarity(item)"
          >{{ item.plantVarietyName }}</el-button>
          <!-- shwang@casdelta.com -->
        </div>
        <div v-if="plantVarityList.length > 8" class="value">
          <el-select
            v-model="plantVarietyObj"
            value-key="plantVarietyNo"
            @change="choosePlantVarity"
          >
            <el-option
              v-for="(item, index) in plantVarityList"
              :key="index"
              :label="item.plantVarietyName"
              :value="item"
            />
          </el-select>
        </div>
      </div>
      <div class="search-item">
        <div class="label">生长阶段名称：</div>
        <div class="value">
          <el-button
            v-for="(item, index) in growthStageList"
            :key="index"
            type="info"
            plain
            size="mini"
            :class="{ active: growthPhaseNo == item.growthPhaseNo }"
            @click="chooseGrowthStage(item)"
          >{{ item.growthPhaseName }}</el-button>
        </div>
      </div>
    </div>
    <div class="data-container">
      <div v-for="(item,index) in diseseList" :key="index" class="data-item">
        <Title :title="'病害名称：' + item.diseaseName" size="big" />
        <div class="data-btn">
          <!--          <el-button type="primary">buttonCont</el-button>-->
          <el-button
            v-if="judgePermission(11, 'edit')"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="editDisList(item)"
          />
          <el-button
            v-if="judgePermission(11, 'delete')"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="delDisList(item.diseaseNo)"
          />
        </div>
        <div class="content" :title="item.diseaseDescribe">
          {{ item.diseaseDescribe }}
          <br />
          <!--           防治方法：{{ item.handle }}-->
        </div>
        <div class="pic-list">
          <div v-for="(items,indexs) in item.diseaseImageList" :key="indexs" class="pic-item">
            <!-- <img :src="'data:image/png;base64,' + items.data" :alt="'data:image/png;base64,' + items.data" /> -->
            <el-image
              :src="'data:image/png;base64,' + items.data"
              :preview-src-list="['data:image/png;base64,' + items.data]"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="阶段病害" :visible.sync="dialogFormVisible" width="40%" :before-close="cancel">
      <el-form
        ref="formData"
        id="uploadForm"
        :model="formData"
        onsubmit="return false;"
        target="frameName"
        name="fileinfo"
        method="post"
        enctype="multipart/form-data"
        :rules="rules"
      >
        <el-form-item label="品种名称" prop="plantVarietyNo" class="w100p">
          <!-- <el-radio-group v-model="formData.plantVarietyNo" @change="choosePlantVaritys">
            <el-radio-button v-for="(item, index) in plantVarityList" :key="index" :label="item.plantVarietyNo">{{ item.plantVarietyName }}</el-radio-button>
          </el-radio-group>-->
          <el-select v-model="formData.plantVarietyNo" @change="choosePlantVaritys">
            <el-option
              v-for="(item, index) in plantVarityList"
              :key="index"
              :label="item.plantVarietyName"
              :value="item.plantVarietyNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="阶段名称" prop="growthPhaseNo" class="w100p">
          <el-radio-group v-model="formData.growthPhaseNo">
            <el-radio-button
              v-for="(item, index) in growthStageList"
              :key="index"
              :label="item.growthPhaseNo"
            >{{ item.growthPhaseName }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="病害名称" prop="diseaseName" class="w100p">
          <el-input v-model="formData.diseaseName" type="text" name="diseaseName" />
        </el-form-item>
        <el-form-item label="病害描述" prop="diseaseDescribe" class="w100p">
          <el-input v-model="formData.diseaseDescribe" type="text" name="diseaseDescribe" />
        </el-form-item>
        <el-form-item label="病害图片" class="w100p">
          <div class="img_box">
            <div
              v-for="(item,index) of imgList"
              v-show="imgList.length!=0"
              :key="index"
              class="img_size"
            >
              <img v-if="item.file.type.indexOf('image') !== -1" :src="item.file.src" />
              <div class="remove_logo" @click="fileDel(index)">×</div>
            </div>
            <div v-show="addState" class="add_img" @click="fileClick">
              <span>+</span>
            </div>
            <input
              id="inpu"
              ref="file"
              name="files"
              style="display: none;"
              type="file"
              accept="image/*"
              @change="fileChange($event)"
            />
          </div>
          <iframe width="0" height="0" name="frameName"></iframe>
        </el-form-item>

        <el-form-item label="处理方法" class="w100p">
          <el-input
            v-model="formData.handle"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            name="handle"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="zh-button-one" @click="cancel">取 消</el-button>
        <el-button class="zh-button-two" type="primary" @click="submit('formData')">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看图片" :visible.sync="dialogVisible" width="40%">
      <img style="width: 100%;" :src="'data:image/png;base64,' + imgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import Title from "@/components/Title/index";
import ActionBar from "@/components/ActionBar/index";
// import mixin from "@/utils/mixins"
import { mymixin } from "@/utils/mixins";
import api from "@/api/digital-production/crop-model/stage-disease-manage";
import axios from "axios";
import { mapGetters } from "vuex";

export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "stage-disease-manage",
  components: {
    Title,
    ActionBar
  },
  mixins: [mymixin],
  data() {
    return {
      rules: {
        plantVarietyNo: [
          { required: true, message: "请输入品种名称", trigger: "blur" }
        ],
        growthPhaseNo: [
          { required: true, message: "请选择阶段名称", trigger: "blur" }
        ],
        diseaseName: [
          { required: true, message: "请输入病害名称", trigger: "blur" }
        ],
      },
      dataList: [{}, {}, {}, {}],
      plantVarityList: [], // 品种列表
      growthStageList: [], // 生长阶段
      plantVarietyObj: {},
      plantVarietyNo: "",
      growthPhaseNo: "",
      diseseList: [],
      // dialogFormVisible: true,
      imgList: [],
      addState: true,
      formDatas: null,
      plantList: [],
      dialogVisible: false,
      imgUrl: ""
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    imgList() {
      if (this.imgList.length === 3) {
        this.addState = false;
      } else {
        this.addState = true;
      }
    },
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(()=>{
          this.$refs.formData.clearValidate()
        })
      }
    }
  },
  mounted() {
    this.getSetect();
    // this.getTableDataList()
  },
  methods: {
    async getTableDataList(e) {
      const { data: res } = await api.queryPageList(e || 1);
      this.diseseList = res;
      res.forEach(item => {
        this.$set(item, "diseaseImageList", []);
        if (item.diseaseImageIdList) {
          item.diseaseImageIdList.forEach(async items => {
            item.diseaseImageList.push(await this.diseaseImage(items));
          });
        }
      });
      this.resetActionBar();
    },
    async diseaseImage(e) {
      const { data: res } = await api.diseaseImage(e);
      return res;
    },
    diseaseImgMax(e) {
      this.dialogVisible = true;
      this.imgUrl = e;
    },
    async getSetect() {
      const { data: plant } = await api.queryWithPhaseByCondition();
      this.plantVarityList = plant;
      this.choosePlantVarity(this.plantVarityList[0]);
      // if (this.growthStageList.length > 0) {
      //   this.chooseGrowthStage({ growthPhaseNo: this.growthStageList[0].growthPhaseNo })
      // }
    },
    async choosePlantVarity(val) {
      // this.getTableDataList()
      this.plantVarietyNo = val.plantVarietyNo;
      const { data: plant } = await api.queryPlantNo({
        plantVarietyNo: val.plantVarietyNo
      });
      this.growthStageList = plant;
      this.chooseGrowthStage({
        growthPhaseNo: this.growthStageList[0].growthPhaseNo
      });
    },
    async choosePlantVaritys(val) {
      // this.getTableDataList()
      this.plantVarietyNo = val;
      const { data: plant } = await api.queryPlantNo({ plantVarietyNo: val });
      this.growthStageList = plant;
    },
    chooseGrowthStage(val) {
      this.growthPhaseNo = val.growthPhaseNo;
      this.getTableDataList(val.growthPhaseNo);
    },
    fileClick() {
      document.getElementById("inpu").click();
    },
    fileChange(el) {
      // const list = this.$refs.file.files;
      if (!el.target.files[0].size) return;
      this.fileList(el.target);
      el.target.value = "";
    },
    fileList(fileList) {
      let files = fileList.files;
      for (let i = 0; i < files.length; i++) {
        // 判断是否为文件夹
        if (files[i].type !== "") {
          this.fileAdd(files[i]);
        } else {
          // 文件夹处理
          this.folders(fileList.items[i]);
        }
      }
    },
    // 文件夹处理
    folders(files) {
      let _this = this;
      // 判断是否为原生file
      if (files.kind) {
        files = files.webkitGetAsEntry();
      }
      files.createReader().readEntries(function(file) {
        for (let i = 0; i < file.length; i++) {
          if (file[i].isFile) {
            _this.foldersAdd(file[i]);
          } else {
            _this.folders(file[i]);
          }
        }
      });
    },
    foldersAdd(entry) {
      let _this = this;
      entry.file(function(file) {
        _this.fileAdd(file);
      });
    },
    fileAdd(file) {
      // 总大小
      this.size = this.size + file.size;
      let reader = new FileReader();
      reader.vue = this;
      reader.readAsDataURL(file);
      reader.onload = function() {
        file.src = this.result;
        this.vue.imgList.push({
          file
        });
      };
    },
    fileDel(index) {
      this.imgList.splice(index, 1);
    },
    bytesToSize(bytes) {
      if (bytes === 0) return "0 B";
      let k = 1000; // or 1024
      let sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      let i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
    },
    uploadImage: function() {},
    async delDisList(e) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          api.delList(e).then(res => {
            if (res.code === 1) {
              this.getTableDataList(this.growthPhaseNo);
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            } else {
              this.$message({
                type: "success",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    base64ToFile(data) {
      let arr = ('data:image/png;base64,' + data.data).split(','); 
      // 获取类型
      let mime = arr[0].match(/:(.*?);/)[1];
      // 解析base字符串
      let bstr = atob(arr[1]); 
      let n = bstr.length; 
      // base64文件数据读取
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      let file = new File([u8arr], data.imageType+'.png', { type: mime });
      file.src = 'data:image/png;base64,' + data.data
      return { file }
    },
    editDisList(e) {
      this.type = 'edit'
      this.formData = { ...e, growthPhaseNo: e.growthPhaseNoList[0] };
      this.imgList = e.diseaseImageList.map(el => {
        return this.base64ToFile(el)
      })

      this.dialogFormVisible = true;
    },
    add() {
      this.addActive = false;
      this.type = 'add'
      this.imgList = []
      this.dialogFormVisible = true;
    },
    submit() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          var form = document.forms.namedItem("fileinfo");
          this.formDatas = new FormData(form);
          let organizationNo = sessionStorage.organizationNo;
          this.formDatas.append("organizationNo", organizationNo);
          this.formDatas.append("plantVarietyNo", this.formData.plantVarietyNo);
          this.formDatas.append("growthPhaseNoList", [this.formData.growthPhaseNo]);
          this.formData.diseaseId && this.formDatas.append("diseaseId", this.formData.diseaseId);
          this.formData.diseaseNo && this.formDatas.append("diseaseNo", this.formData.diseaseNo);
          // this.formDatas.append("growthPhaseNo", '1111');
          for (var i = 0; i < this.imgList.length; i++) {
            this.formDatas.append("files", this.imgList[i].file);
            // console.log(this.imgList);
          }
          axios({
            url: this.$baseurl.webServiceUrl + "v3/modelTenant/disease/" + this.type,
            // url: 'http://192.168.1.85:40029' + "/disease/add",
            // url: "http://192.168.1.85:8080/fileArg/receive",
            method: "post",
            headers: {
              databaseName: sessionStorage.databaseName,
              accessToken: sessionStorage.token,
              enctype: "multipart/form-data"
            },
            data: this.formDatas
          }).then(res => {
            if (res.data.code === 1) {
              this.getTableDataList(this.growthPhaseNo);
              this.$message.success("添加成功！");
            } else {
              this.$message.warning("添加失败！");
            }
          });
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .search-item-list {
    height: 100px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .search-item {
      height: 30px;
      line-height: 30px;
      display: flex;
      margin-bottom: 10px;
    }
  }

  .data-container {
    height: calc(100% - 80px);
    display: flex;
    flex-wrap: wrap;

    .data-item {
      width: calc(100% - 10px);
      height: 370px;
      margin-bottom: 20px;
      box-shadow: 0px 0px 32px inset rgba(24, 140, 158, 0.8);
      position: relative;
      .data-btn {
        position: absolute;
        bottom: 20px;
        right: 20px;
      }
      &:nth-child(2n) {
        margin-left: 20px;
      }

      .content {
        padding: 10px 20px;
        font-size: 16px;
        max-height: 21%;
        height: 21%;
        // white-space:wrap;
        /*文字超出宽度则显示ellipsis省略号*/
        // text-overflow:ellipsis;
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        text-overflow: ellipsis;
      }

      .pic-list {
        display: flex;
        justify-content: space-evenly;
        padding: 10px;
        overflow-x: auto;
        .pic-item {
          width: calc(33% - 20px);
          height: 160px;
          // border: 1px solid #ccc;
          text-align: center;
          img {
            width: auto;
            height: auto;
            max-height: 100%;
            max-width: 100%;
          }
          ::v-deep .el-image {
            width: auto;
            height: auto;
            max-height: 100%;
            max-width: 54%;
          }
          &:not(:last-child) {
            margin-right: 30px;
          }
        }
      }
    }
  }
}

.img_box {
  display: flex;
  width: 100%;

  .img_size {
    position: relative;
    max-width: 30%;
    height: 120px;
    margin-right: 10px;

    img {
      height: 100%;
      max-width: 100%;
    }
    .remove_logo {
      position: absolute;
      top: 0;
      right: 0;
      height: auto;
      line-height: initial;
      font-size: 21px;
      cursor: pointer;
    }
  }
}

.add_img {
  margin-left: 10px;

  span {
    font-size: 34px;
    display: inline-block;
    border: 1px solid #0b8e8b;
    box-sizing: border-box;
    height: 40px;
    width: 40px;
    text-align: center;
    line-height: 32px;
    border-radius: 4px;
    font-family: "微軟正黑體 Light", "楷体", "宋体";
  }
}
.value {
  ::v-deep {
    .el-button {
      border: 1.5px solid #33eadc;
    }
    .el-button--info.is-plain {
      color: #ffffff;
      background: initial;
      border-color: #71bdd5;
    }
  }
}
.active {
  color: #33eadc !important;
  background: initial;
  box-shadow: inset 0px 0px 6px 0px #33eadc !important;
  border-color: #33eadc !important;
}
::v-deep .el-button--info.is-plain:focus,
.el-button--info.is-plain:hover {
  color: #33eadc;
  background: initial;
  box-shadow: inset 0px 0px 6px 0px #33eadc;
  border-color: #33eadc;
}
::v-deep .el-image-viewer__wrapper {
  position: fixed;
  top: 11vh;
  right: 0;
  bottom: 0;
  left: 11vw;
  overflow: hidden;
  // height: 89vh;
}
</style>
